/**
 * @file linked_queue.c
 * File implementing a generic LinkedQueue data structure
 * @author Denis Ollier
 * @ingroup LinkedQueue
 */

#include <linked_queue.h>
#include <stdlib.h>

void linked_queue_dispose (linked_queue qu)
{
	free(qu);
}

unsigned int linked_queue_is_empty (linked_queue qu)
{
	if (qu->first_cell == NULL)
		return 1;
	return 0;
}

linked_queue linked_queue_new (void)
{
	linked_queue new_linked_queue = (linked_queue) malloc(sizeof(struct linked_queue));
	if (new_linked_queue != NULL)
	{
		new_linked_queue->first_cell = NULL;
		new_linked_queue->last_cell = NULL;
	}
	return new_linked_queue;
}

unsigned int linked_queue_offer (linked_queue qu, void* element)
{
	qu->last_cell->next = (struct cell*) malloc(sizeof(struct cell));
	if (qu->last_cell->next != NULL)
	{
		qu->last_cell->next->element = element;
		qu->last_cell->next->next = NULL;
		qu->last_cell = qu->last_cell->next;
		return 1;
	}
	return 0;
}

void* linked_queue_peek (linked_queue qu)
{
	return qu->first_cell->element;
}

void* linked_queue_poll (linked_queue qu)
{
	void* result;
	struct cell* aux;

	if (qu->first_cell != NULL)
	{
		result = qu->first_cell->element;
		aux = qu->first_cell;
		qu->first_cell = qu->first_cell->next;
		free(aux);
		return result;
	}
	return NULL;
}

int linked_queue_search (linked_queue qu, void* element)
{
	unsigned int result;
	struct cell* aux;

	aux = qu->first_cell;
	for (result = 0; aux != NULL; result++)
	{
		if (aux->element == element)
			return result;
		aux = aux->next;
	}
	return -1;
}
